package com.hyz.reggie.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hyz.reggie.common.RedisKeys;
import com.hyz.reggie.dto.SetmealDto;
import com.hyz.reggie.pojo.R;
import com.hyz.reggie.pojo.Setmeal;
import com.hyz.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @GetMapping("/page")
    public R findByPage(Integer page, Integer pageSize, String name) {
        IPage<SetmealDto> iPage = setmealService.findByPage(page, pageSize, name);
        return R.success(iPage);
    }

    @PostMapping
    @CacheEvict(value ="SETMEAL_CODE",key = "'RedisKeys.SETMEAL_'+#setmealDto.status+'_'+#setmealDto.categoryId" )
    public R add(@RequestBody SetmealDto setmealDto) {
        setmealService.add(setmealDto);
        return R.success("添加成功~");
    }

    @GetMapping("/{id}")
    public R findById(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.findById(id);
        return R.success(setmealDto);
    }

    @DeleteMapping
    @CacheEvict(value ="SETMEAL_CODE",allEntries = true)
    public R deleteIds(Long[] ids) {
        setmealService.deleteIds(ids);
        return R.success("删除成功~");
    }

    @PutMapping
    @CacheEvict(value ="SETMEAL_CODE",key = "'RedisKeys.SETMEAL_'+#setmealDto.status+'_'+#setmealDto.categoryId" )
    public R modifySetmeal(@RequestBody SetmealDto setmealDto) {
        if (setmealDto == null) {
            return R.error("无效操作~");
        }
        setmealService.modifySetmeal(setmealDto);
        return R.success("修改成功~");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value ="SETMEAL_CODE",allEntries = true)
    public R startOrEnd(@PathVariable Integer status, Long[] ids) {
        setmealService.startOrEnd(status, ids);
        return status == 1 ? R.success("起售成功~") : R.success("停售成功~");
    }

    @GetMapping("/list")
    @Cacheable(value = "SETMEAL_CODE",key = "'RedisKeys.SETMEAL_'+#setmeal.status+'_'+#setmeal.categoryId")
    public R getList(Setmeal setmeal) {
        List<Setmeal> list = setmealService.getList(setmeal);
        return R.success(list);
    }
}
